package com.suarte.webapp.action;

import com.suarte.core.*;
import com.suarte.core.Invoice;
import com.suarte.core.service.CompanyManager;
import com.suarte.core.service.ContactManager;
import com.suarte.core.service.ExchangeRateManager;
import com.suarte.core.service.InvoiceManager;
import com.suarte.core.service.QuotationManager;
import com.suarte.core.service.WorkOrderManager;
import com.suarte.utils.MathUtils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.appfuse.service.GenericManager;
import javax.faces.component.UIParameter;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.servlet.http.HttpServletRequest;
import org.appfuse.model.User;
import org.apache.commons.lang.StringUtils;

/**
 * @date   Dec 21, 2010
 * @author Ggutierrez
 */
public class QuotationForm extends BasePage implements Serializable {

    private QuotationManager quotationManager;
    private GenericManager<Currency, Long> currencyManager;
    private CompanyManager companyManager;
    private ContactManager contactManager;
    private GenericManager<PaymentMethod, Long> paymentMethodManager;
    private GenericManager<DeliveryTime, Long> deliveryTimeManager;
    private GenericManager<Product, Long> productManager;
    private GenericManager<Guarantee, Long> guaranteeManager;
    private GenericManager<Employee, Long> employeeManager;
    private ExchangeRateManager exchangeRateManager;
    private InvoiceManager invoiceManager;
    private WorkOrderManager workOrderManager;
    private Quotation quotation = new Quotation();
    private Long id;
    private Company company;
    private Long productId;
    private String productDescription;
    private Float productPrice;
    private Float productMeasure;
    private Float myMeasure;
    private Integer quantity;
    private Long detailId;
    private List<QuotationDetail> deletes = new ArrayList();
    private User requestUser;
    private WorkOrder workOrder;
    private Employee responsible;
    private Boolean isView = false;
    private List<Contact> contacts;
    private Contact contact;
    private List<Company> companies;
    private String otherProductDescription;
    private Float otherProductPrice;
    private Integer otherProductQuantity;
    
    public QuotationForm() {
    }

    public void setQuotationManager(QuotationManager quotationManager) {
        this.quotationManager = quotationManager;
    }

    public void setCurrencyManager(GenericManager<Currency, Long> currencyManager) {
        this.currencyManager = currencyManager;
    }

    public void setCompanyManager(CompanyManager companyManager) {
        this.companyManager = companyManager;
    }

    public void setContactManager(ContactManager contactManager) {
        this.contactManager = contactManager;
    }

    public void setPaymentMethodManager(GenericManager<PaymentMethod, Long> paymentMethodManager) {
        this.paymentMethodManager = paymentMethodManager;
    }

    public void setDeliveryTimeManager(GenericManager<DeliveryTime, Long> deliveryTimeManager) {
        this.deliveryTimeManager = deliveryTimeManager;
    }

    public void setEmployeeManager(GenericManager<Employee, Long> employeeManager) {
        this.employeeManager = employeeManager;
    }

    public void setExchangeRateManager(ExchangeRateManager exchangeRateManager) {
        this.exchangeRateManager = exchangeRateManager;
    }

    public void setInvoiceManager(InvoiceManager invoiceManager) {
        this.invoiceManager = invoiceManager;
    }

    public Quotation getQuotation() {
        return quotation;
    }

    public void setQuotation(Quotation quotation) {
        this.quotation = quotation;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String add() {       
        companies = companyManager.findCompanies();

        if (id != null) {
            quotation = quotationManager.get(id);
        } else {
            Date date = new Date();
            Currency currency = currencyManager.get(2L); // Default currency
            ExchangeRate exchangeRate = exchangeRateManager.findByDate(date, currency, null, ExchangeRateType.DIARIA);

            quotation = new Quotation();
            if (exchangeRate == null) {
                exchangeRate = exchangeRateManager.findByDate(date, currency, null, ExchangeRateType.MENSUAL);
            }
            if (exchangeRate == null) {
                exchangeRate = exchangeRateManager.findByDate(date, currency, null, ExchangeRateType.ANUAL);
            }

            if (exchangeRate != null) {
                if (exchangeRate.getFromCurrency().equals(quotation.getCurrency())) {
                    quotation.setExchangeCurrency(exchangeRate.getToCurrency());
                } else if (exchangeRate.getToCurrency().equals(quotation.getCurrency())) {
                    quotation.setExchangeCurrency(exchangeRate.getFromCurrency());
                }
                quotation.setExchangeRate(exchangeRate.getRate());
            } else {
                Currency exchangeCurrency = currencyManager.get(1L); // Default contrary currency
                quotation.setExchangeCurrency(exchangeCurrency);
            }

            quotation.setCurrency(currency);
            quotation.setTransDate(date);
        }

        isView = false;
        return "add";
    }

    public String delete() {
        quotationManager.remove(quotation.getId());
        addMessage("quotation.deleted");

        return "list";
    }

    public String edit() {       
        companies = companyManager.findCompanies();
        if (id != null) {
            quotation = quotationManager.get(id);
            contacts = contactManager.findByCompany(quotation.getCompany());
        } else {
            quotation = new Quotation();
            quotation.setTransDate(new Date());
        }

        if (quotation.getStatus().equals(QuotationStatus.SOLICITADA)) {
            isView = false;
            return "edit";
        }

        isView = true;
        return "view";
    }

    public String save() {
        boolean isNew = (quotation.getId() == null);
        HttpServletRequest request = getRequest();
        Date date = new Date();
        requestUser = userManager.getUserByUsername(request.getRemoteUser());
        Float qSubTotal = 0f;
        Float qTotal = 0f;
        Float qTax = 0f;
        
        if (StringUtils.isBlank(quotation.getDescription())){
            addError("quotation.description.required");
            return "fail";
        }

        for (QuotationDetail detail : quotation.getDetails()) {
            // Recalculate total
            detail.setSubTotal(detail.getPrice() * detail.getQuantity());
            detail.setTax(detail.getSubTotal() * 0.15f);
            detail.setTotal(detail.getSubTotal() + detail.getTax());

            qSubTotal += detail.getSubTotal();
            qTax += detail.getTax();
            qTotal += detail.getTotal();
            detail.setModifiedBy(requestUser);
            detail.setModifiedOn(new Date());

            if (isNew) {
                detail.setCreatedBy(requestUser);
                detail.setCreatedOn(new Date());
            }
        }

        if (isNew) {
            quotation.setCreatedBy(requestUser);
            quotation.setCreatedOn(date);
        }

        quotation.setModifiedBy(requestUser);
        quotation.setModifiedOn(date);
        quotation.setSubtotal(qSubTotal);
        quotation.setTax(qTax);
        quotation.setTotalCost(qTotal);

        if (quotation.getExchangeRate() != null) {
            Float equivalent = 0f;
            if (quotation.getCurrency() != null && quotation.getCurrency().getSymbol().equals("C$")) {
                equivalent = round(quotation.getTotalCost() / quotation.getExchangeRate(), 2);
                quotation.setLocalAmount(quotation.getTotalCost());
                quotation.setForeignAmount(equivalent);
            } else {
                equivalent = round(quotation.getTotalCost() * quotation.getExchangeRate(), 2);
                quotation.setForeignAmount(quotation.getTotalCost());
                quotation.setLocalAmount(equivalent);
            }

            quotation.setEquivalentAmount(equivalent);
        }

        quotationManager.deleteDetails(deletes);
        quotationManager.save(quotation);

        String key = (isNew) ? "quotation.added" : "quotation.updated";
        addMessage(key);

        getRequestMap().put("printQuo", true);

        if (isNew) {
            return "list";
        } else {
            return "edit";
        }
    }

    public String approve() {
        if (responsible == null) {
            String key = "quotation.responsible.null";
            addMessage(key);
            return "fail";
        }

        HttpServletRequest request = getRequest();
        Date date = new Date();
        requestUser = userManager.getUserByUsername(request.getRemoteUser());

        // Calculate delivery days
        Integer days = quotation.getDeliveryTime().getDays();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, days.intValue());
        Date deliveryDate = calendar.getTime();

        workOrder = new WorkOrder();
        workOrder.setQuotation(quotation);
        workOrder.setReceptionDate(new Date());
        workOrder.setDescription(quotation.getDescription());
        workOrder.setEmployee(responsible);
        workOrder.setCreatedBy(requestUser);
        workOrder.setModifiedBy(requestUser);
        workOrder.setCreatedOn(date);
        workOrder.setModifiedOn(date);
        workOrder.setDeliveryDate(deliveryDate);

        for (QuotationDetail qDetail : quotation.getDetails()) {
            WorkOrderDetail workOrderDetail = new WorkOrderDetail();
            workOrderDetail.setQuotationDetail(qDetail);
            workOrder.addDetail(workOrderDetail);
        }
        workOrderManager.save(workOrder);

        quotation.setStatus(QuotationStatus.APROBADA);
        quotation.setDeliveryStatus(QuotationStatus.EN_PROCESO);
        quotationManager.save(quotation);

        String key = "quotation.approved";
        addMessage(key);

        isView = true;
        return "edit";
    }

    public String generateInvoice() {
        HttpServletRequest request = getRequest();
        Date date = new Date();
        requestUser = userManager.getUserByUsername(request.getRemoteUser());

        Invoice invoice = new Invoice();
        invoice.setCompany(quotation.getCompany());
        invoice.setContact(quotation.getContact());
        invoice.setDescription(quotation.getDescription());
        invoice.setQuotation(quotation);
        invoice.setDate(new Date());
        invoice.setSubTotal(MathUtils.round(quotation.getSubtotal()));
        invoice.setTax(MathUtils.round(quotation.getTax()));
        invoice.setTotal(MathUtils.round(quotation.getTotalCost()));
        invoice.setCurrency(quotation.getCurrency());
        invoice.setExchangeCurrency(quotation.getExchangeCurrency());
        invoice.setExchangeRate(quotation.getExchangeRate());
        invoice.setEquivalentAmount(MathUtils.round(quotation.getEquivalentAmount()));
        invoice.setCreatedBy(requestUser);
        invoice.setCreatedOn(date);
        invoice.setModifiedBy(requestUser);
        invoice.setModifiedOn(date);
        invoice.setStatus(DocumentStatus.ACTIVA);

        if (quotation.getCurrency() != null && quotation.getCurrency().getSymbol().equals("C$")) {
            invoice.setLocalAmount(MathUtils.round(quotation.getTotalCost()));
            invoice.setForeignAmount(MathUtils.round(quotation.getEquivalentAmount()));
        } else if (quotation.getCurrency() != null && quotation.getCurrency().getSymbol().equals("$")) {
            invoice.setLocalAmount(MathUtils.round(quotation.getEquivalentAmount()));
            invoice.setForeignAmount(MathUtils.round(quotation.getTotalCost()));
        }

        // Calculate delivery days
        Integer days = quotation.getCompany().getCreditDays();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, days.intValue());
        Date expirationDate = calendar.getTime();

        invoice.setExpirationDate(expirationDate);

        for (QuotationDetail qDetail : quotation.getDetails()) {
            InvoiceDetail invoiceDetail = new InvoiceDetail();
            invoiceDetail.setQuotationDetail(qDetail);
            invoice.addDetail(invoiceDetail);
        }
        invoiceManager.save(invoice);

        if (quotation.getCurrency().getSymbol().equals("$")) {
            quotation.getCompany().debit(MathUtils.round(quotation.getTotalCost()), MathUtils.round(quotation.getEquivalentAmount()));
        } else if (quotation.getCurrency().getSymbol().equals("C$")) {
            quotation.getCompany().debit(MathUtils.round(quotation.getEquivalentAmount()), MathUtils.round(quotation.getTotalCost()));
        }
        companyManager.save(quotation.getCompany());

        quotation.setStatus(QuotationStatus.FACTURADA);
        quotation.setModifiedOn(date);
        quotation.setModifiedBy(requestUser);
        quotationManager.save(quotation);

        String key = "quotation.invoice";
        addMessage(key);

        isView = true;
        return "edit";
    }

    public String cancel() {
        quotation.setStatus(QuotationStatus.CANCELADA);
        quotationManager.save(quotation);

        String key = "quotation.updated";
        addMessage(key);

        return "edit";
    }

    public String reject() {
        quotation.setStatus(QuotationStatus.RECHAZADA);
        quotationManager.save(quotation);

        String key = "quotation.updated";
        addMessage(key);

        return "edit";
    }

    public void addProduct(ActionEvent e) {
        System.out.println("Entra add product");
        Float quotationSubTotal = 0f;
        Float quotationTax = 0f;
        Float quotationTotal = 0f;
        if (quantity == null) {
            String key = "quotation.product.quantity.missing";
            addMessage(key);
        } else if (productId == null) {
            String key = "quotation.product.missing";
            addMessage(key);
        } else if (myMeasure == null) {
            String key = "quotation.product.measure.missing";
            addMessage(key);
        } else {
            Product product = productManager.get(productId);

            Float subTotal = 0f;
            Float tax = 0f;
            Float total = 0f;
            Float price = 0f;
            Float localPrice = productPrice * (quotation.getExchangeRate() != null ? quotation.getExchangeRate() : 1f);

            if (quotation.getCurrency() != null && quotation.getCurrency().getSymbol().equals("C$")) {
                price = localPrice;
            } else {
                price = productPrice;
            }

            subTotal = price * quantity * myMeasure;
            tax = subTotal * 0.15f;
            total = subTotal + tax;

            QuotationDetail detail = new QuotationDetail();
            detail.setProduct(product);
            detail.setPrice(productPrice);
            detail.setLocalPrice(localPrice);
            detail.setForeignPrice(productPrice);
            detail.setQuantity(quantity);
            detail.setMeasure(myMeasure);
            detail.setSubTotal(subTotal);
            detail.setTotal(total);

            if (quotation.getCurrency() != null && quotation.getCurrency().getSymbol().equals("C$")) {
                detail.setLocalTotal(total);
                detail.setForeignTotal(total / (quotation.getExchangeRate() != null ? quotation.getExchangeRate() : 1f));
            } else {
                detail.setForeignTotal(total);
                detail.setLocalTotal(total * (quotation.getExchangeRate() != null ? quotation.getExchangeRate() : 1f));
            }

            quotationSubTotal = quotation.getSubtotal() == null ? 0f : quotation.getSubtotal();
            quotationSubTotal += subTotal;
            quotationTax = quotation.getTax() == null ? 0f : quotation.getTax();
            quotationTax += tax;
            quotationTotal = quotation.getTotalCost() == null ? 0f : quotation.getTotalCost();
            quotationTotal += total;
            quotation.setSubtotal(quotationSubTotal);
            quotation.setTax(quotationTax);
            quotation.setTotalCost(quotationTotal);
            quotation.addDetail(detail);

            if (quotation.getExchangeRate() != null) {
                Float equivalent = 0f;
                if (quotation.getCurrency() != null && quotation.getCurrency().getSymbol().equals("C$")) {
                    equivalent = round(quotationTotal / quotation.getExchangeRate(), 2);
                } else {
                    equivalent = round(quotationTotal * quotation.getExchangeRate(), 2);
                }
                quotation.setEquivalentAmount(equivalent);
            }
        }
        quantity = null;
        myMeasure = null;
    }

    public void addAnotherProduct(ActionEvent e) {
        System.out.println("Entra another product");
        Float quotationSubTotal = 0f;
        Float quotationTax = 0f;
        Float quotationTotal = 0f;
        if (otherProductQuantity == null) {
            String key = "quotation.product.quantity.missing";
            addMessage(key);
        } else if (otherProductDescription == null) {
            String key = "quotation.product.missing";
            addMessage(key);
        } else if (otherProductPrice == null) {
            String key = "quotation.product.price.missing";
            addMessage(key);
        } else {
            Float subTotal = 0f;
            Float tax = 0f;
            Float total = 0f;
            Float price = 0f;
            Float localPrice = 0f;
            Float foreignPrice = 0f;
            if (quotation.getCurrency() != null && quotation.getCurrency().getSymbol().equals("C$")){
                localPrice = otherProductPrice;
                foreignPrice = otherProductPrice / (quotation.getExchangeRate() != null ? quotation.getExchangeRate() : 1f);
            } else {
                localPrice = otherProductPrice * (quotation.getExchangeRate() != null ? quotation.getExchangeRate() : 1f);
                foreignPrice = otherProductPrice;
            }

            price = otherProductPrice;

            subTotal = price * otherProductQuantity;
            tax = subTotal * 0.15f;
            total = subTotal + tax;

            QuotationDetail detail = new QuotationDetail();
            detail.setItemDescription(otherProductDescription);
            detail.setPrice(otherProductPrice);
            detail.setLocalPrice(localPrice);
            detail.setForeignPrice(foreignPrice);
            detail.setQuantity(otherProductQuantity);
            detail.setMeasure(null);
            detail.setSubTotal(subTotal);
            detail.setTotal(total);

            if (quotation.getCurrency() != null && quotation.getCurrency().getSymbol().equals("C$")) {
                detail.setLocalTotal(total);
                detail.setForeignTotal(total / (quotation.getExchangeRate() != null ? quotation.getExchangeRate() : 1f));
            } else {
                detail.setForeignTotal(total);
                detail.setLocalTotal(total * (quotation.getExchangeRate() != null ? quotation.getExchangeRate() : 1f));
            }

            quotationSubTotal = quotation.getSubtotal() == null ? 0f : quotation.getSubtotal();
            quotationSubTotal += subTotal;
            quotationTax = quotation.getTax() == null ? 0f : quotation.getTax();
            quotationTax += tax;
            quotationTotal = quotation.getTotalCost() == null ? 0f : quotation.getTotalCost();
            quotationTotal += total;
            quotation.setSubtotal(quotationSubTotal);
            quotation.setTax(quotationTax);
            quotation.setTotalCost(quotationTotal);
            quotation.addDetail(detail);

            if (quotation.getExchangeRate() != null) {
                Float equivalent = 0f;
                if (quotation.getCurrency() != null && quotation.getCurrency().getSymbol().equals("C$")) {
                    equivalent = round(quotationTotal / quotation.getExchangeRate(), 2);
                } else {
                    equivalent = round(quotationTotal * quotation.getExchangeRate(), 2);
                }
                quotation.setEquivalentAmount(equivalent);
            }
        }
        quantity = null;
        myMeasure = null;
    }

    public void deleteProduct(ActionEvent e) {
        UIParameter param = (UIParameter) e.getComponent().getChildren().get(0);
        detailId = Long.valueOf(param.getValue().toString());

        if (detailId != null) {
            QuotationDetail detail = quotation.getDetails().get(detailId.intValue());
            quotation.getDetails().remove(detail);
            deletes.add(detail);
        }

        Float qSubTotal = 0f;
        Float qTotal = 0f;
        Float qTax = 0f;

        for (QuotationDetail detail : quotation.getDetails()) {
            // Recalculate total
            detail.setSubTotal(detail.getPrice() * detail.getQuantity());
            detail.setTax(detail.getSubTotal() * 0.15f);
            detail.setTotal(detail.getSubTotal() + detail.getTax());

            qSubTotal = (qSubTotal + detail.getSubTotal());
            qTax += detail.getTax();
            qTotal += detail.getTotal();
            detail.setModifiedBy(requestUser);
            detail.setModifiedOn(new Date());
        }

        quotation.setSubtotal(qSubTotal);
        quotation.setTax(qTax);
        quotation.setTotalCost(qTotal);

        if (quotation.getExchangeRate() != null) {
            Float equivalent = 0f;
            if (quotation.getCurrency() != null && quotation.getCurrency().getSymbol().equals("C$")) {
                equivalent = round(qTotal / quotation.getExchangeRate(), 2);
            } else {
                equivalent = round(qTotal * quotation.getExchangeRate(), 2);
            }
            quotation.setEquivalentAmount(equivalent);
        }
    }

    public List<Currency> getCurrencies() {
        return currencyManager.getAll();
    }

    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }

    public List<Company> getCompanies() {
        return companies;
    }

    public List<Contact> getContacts() {
        return contacts;
    }

    public List<PaymentMethod> getPaymentMethods() {
        return paymentMethodManager.getAll();
    }

    public List<DeliveryTime> getDeliveryTimes() {
        return deliveryTimeManager.getAll();
    }

    public List<Guarantee> getGuarantees() {
        return guaranteeManager.getAll();
    }

    public Long getProductId() {
        return productId;
    }

    public void setProductId(Long productId) {
        this.productId = productId;
    }

    public Float getProductMeasure() {
        return productMeasure;
    }

    public void setProductMeasure(Float productMeasure) {
        this.productMeasure = productMeasure;
    }

    public Float getMyMeasure() {
        return myMeasure;
    }

    public void setMyMeasure(Float myMeasure) {
        this.myMeasure = myMeasure;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    public String getProductDescription() {
        return productDescription;
    }

    public void setProductDescription(String productDescription) {
        this.productDescription = productDescription;
    }

    public Float getProductPrice() {
        return productPrice;
    }

    public void setProductPrice(Float productPrice) {
        this.productPrice = productPrice;
    }

    public GenericManager<Product, Long> getProductManager() {
        return productManager;
    }

    public void setProductManager(GenericManager<Product, Long> productManager) {
        this.productManager = productManager;
    }

    public Long getDetailId() {
        return detailId;
    }

    public void setDetailId(Long detailId) {
        this.detailId = detailId;
    }

    public List<QuotationDetail> getDeletes() {
        return deletes;
    }

    public void setDeletes(List<QuotationDetail> deletes) {
        this.deletes = deletes;
    }

    public User getRequestUser() {
        return requestUser;
    }

    public void setRequestUser(User requestUser) {
        this.requestUser = requestUser;
    }

    public GenericManager<Guarantee, Long> getGuaranteeManager() {
        return guaranteeManager;
    }

    public void setGuaranteeManager(GenericManager<Guarantee, Long> guaranteeManager) {
        this.guaranteeManager = guaranteeManager;
    }

    public WorkOrder getWorkOrder() {
        return workOrder;
    }

    public void setWorkOrder(WorkOrder workOrder) {
        this.workOrder = workOrder;
    }

    public Employee getResponsible() {
        return responsible;
    }

    public void setResponsible(Employee responsible) {
        this.responsible = responsible;
    }

    public List<Employee> getResponsibles() {
        return employeeManager.getAll();
    }

    public WorkOrderManager getWorkOrderManager() {
        return workOrderManager;
    }

    public void setWorkOrderManager(WorkOrderManager workOrderManager) {
        this.workOrderManager = workOrderManager;
    }

    public Boolean getIsView() {
        return isView;
    }

    public void setIsView(Boolean isView) {
        this.isView = isView;
    }

    public void setContacts(List<Contact> contacts) {
        this.contacts = contacts;
    }

    public Contact getContact() {
        return contact;
    }

    public void setContact(Contact contact) {
        this.contact = contact;
    }

    public void setCompanies(List<Company> companies) {
        this.companies = companies;
    }

    public void processCompanyChange(ValueChangeEvent event) throws AbortProcessingException {
        Long oldValue = event.getOldValue() != null ? ((Company) event.getOldValue()).getId() : null;
        Long newValue = event.getNewValue() != null ? ((Company) event.getNewValue()).getId() : null;

        System.out.println("Values : Old: " + oldValue + "; New: " + newValue);

        if ((oldValue != null && !newValue.equals(oldValue)) || oldValue == null) {
            company = companyManager.get(((Company) event.getNewValue()).getId());
            contacts = contactManager.findByCompany(company);
            if (contacts.size() > 0) {
                contact = contacts.get(0);
            }
            FacesContext.getCurrentInstance().renderResponse();
        }

    }

    public void processCurrencyChange(ValueChangeEvent event) throws AbortProcessingException {
        Long oldValue = event.getOldValue() != null ? ((Currency) event.getOldValue()).getId() : null;
        Long newValue = event.getNewValue() != null ? ((Currency) event.getNewValue()).getId() : null;

        System.out.println("Values : Old: " + oldValue + "; New: " + newValue);

        if ((oldValue != null && !newValue.equals(oldValue)) || oldValue == null) {
            Float equivalent = 0f;
            if (newValue.equals(1L)) {
                Currency exchangeCurrency = currencyManager.get(2L);
                quotation.setExchangeCurrency(exchangeCurrency);
                if (quotation.getExchangeRate() != null) {
                    equivalent = round(quotation.getTotalCost() / quotation.getExchangeRate(), 2);
                    quotation.setEquivalentAmount(equivalent);
                }
            } else if (newValue.equals(2L)) {
                Currency exchangeCurrency = currencyManager.get(1L);
                quotation.setExchangeCurrency(exchangeCurrency);
                if (quotation.getExchangeRate() != null) {
                    equivalent = round(quotation.getTotalCost() * quotation.getExchangeRate(), 2);
                    quotation.setEquivalentAmount(equivalent);
                }
            }
            FacesContext.getCurrentInstance().renderResponse();
        }
    }

    public static float round(float Rval, int Rpl) {
        float p = (float) Math.pow(10, Rpl);
        Rval = Rval * p;
        float tmp = Math.round(Rval);
        return (float) tmp / p;
    }

    public String getOtherProductDescription() {
        return otherProductDescription;
    }

    public void setOtherProductDescription(String otherProductDescription) {
        this.otherProductDescription = otherProductDescription;
    }

    public Float getOtherProductPrice() {
        return otherProductPrice;
    }

    public void setOtherProductPrice(Float otherProductPrice) {
        this.otherProductPrice = otherProductPrice;
    }

    public Integer getOtherProductQuantity() {
        return otherProductQuantity;
    }

    public void setOtherProductQuantity(Integer otherProductQuantity) {
        this.otherProductQuantity = otherProductQuantity;
    }
}
